package com.mlst.fmlblipper;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;

import com.google.wave.api.AbstractRobotServlet;
import com.google.wave.api.Blip;
import com.google.wave.api.Event;
import com.google.wave.api.EventType;
import com.google.wave.api.RobotMessageBundle;
import com.google.wave.api.TextView;
import com.google.wave.api.Wavelet;

public class FMLBlipperServlet extends AbstractRobotServlet {

    @Override
    public void processEvents(RobotMessageBundle bundle) {
	final Wavelet wavelet = bundle.getWavelet();

	if (bundle.wasSelfAdded()) {
	    final Blip blip = wavelet.appendBlip();
	    final TextView textView = blip.getDocument();
	    textView.append("Hi, Just type in FML to get random FML stories from www.fmylife.com");
	}

	for (Event e : bundle.getEvents()) {
	    if (e.getType() == EventType.BLIP_SUBMITTED) {
		final String blipText = e.getBlip().getDocument().getText();
		if (blipText != null && blipText.toUpperCase().contains("FML")) {
		    final Blip blip = wavelet.appendBlip();
		    final TextView textView = blip.getDocument();
		    final String fml = getRandomFML();
		    
		    if (fml != null) {
			textView.append(fml);
		    } else {
			textView.append("Oops. I'm having hiccups at the moment. Try again later.");
		    }
		}
	    }
	}
    }

    private String getRandomFML() {
	try {
	    final URL url = new URL("http://api.betacie.com/view/random?language=en&key=readonly");
	    final StringBuilder builder = new StringBuilder();
	    final BufferedReader rd = new BufferedReader(new InputStreamReader(url.openStream()));
	    
	    String s = "";
	    while ((s = rd.readLine()) != null) {
		builder.append(s);
	    }

	    rd.close();

	    return parseResponse(builder.toString());
	} catch (Exception e) {
	    e.printStackTrace();
	}

	return null;
    }

    private String parseResponse(String s) {
	final int start = s.indexOf("<text>") + "<text>".length();
	s = s.substring(start, s.indexOf("</text>", start));
	return s;
    }
}
